package com.xiaoshuidi.cloud.module.system.mq.producer.sms;

import com.xiaoshuidi.cloud.framework.common.core.KeyValue;
import com.xiaoshuidi.cloud.framework.mq.core.bus.AbstractBusProducer;
import com.xiaoshuidi.cloud.module.system.mq.message.sms.SmsChannelRefreshMessage;
import com.xiaoshuidi.cloud.module.system.mq.message.sms.SmsSendMessage;
import com.xiaoshuidi.cloud.module.system.mq.message.sms.SmsTemplateRefreshMessage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.stream.function.StreamBridge;
import org.springframework.integration.support.MessageBuilder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Set;

/**
 * Sms 短信相关消息的 Producer
 *
 * @author zzf
 * @date 2021/3/9 16:35
 */
@Slf4j
@Component
public class SmsProducer extends AbstractBusProducer {

    @Value("${spring.cloud.nacos.discovery.group:DEFAULT_GROUP}")
    private String group;
    @Resource
    private StreamBridge streamBridge;

    /**
     * 发送 {@link SmsChannelRefreshMessage} 消息
     */
    public void sendSmsChannelRefreshMessage() {
        publishEvent(new SmsChannelRefreshMessage(this, getBusId(), selfDestinationService()));
    }

    /**
     * 发送 {@link SmsTemplateRefreshMessage} 消息
     */
    public void sendSmsTemplateRefreshMessage() {
        publishEvent(new SmsTemplateRefreshMessage(this, getBusId(), selfDestinationService()));
    }

    /**
     * 发送 {@link SmsSendMessage} 消息
     *
     * @param logId          短信日志编号
     * @param mobile         手机号
     * @param content        短信内容
     * @param channelId      渠道编号
     * @param apiTemplateId  短信模板编号
     * @param templateParams 短信模板参数
     */
    public void sendSmsSendMessage(Long logId, String mobile, String content,
                                   Long channelId, String apiTemplateId, List<KeyValue<String, Object>> templateParams,
                                   Set<String> shortUrlParamName) {
        SmsSendMessage message = new SmsSendMessage().setLogId(logId).setMobile(mobile)
                .setShortUrlParamName(shortUrlParamName)
                .setContent(content);
        message.setChannelId(channelId).setApiTemplateId(apiTemplateId).setTemplateParams(templateParams);
        streamBridge.send("smsSend-out-0", MessageBuilder.withPayload(message)
                .setHeader("TAGS", group).build());
    }

}
